// Copyright (c) 2024 IndustrialTBB Framework
// Licensed under MIT License

#ifndef ITBB_H_
#define ITBB_H_

/**
 * @file itbb.h
 * @brief IndustrialTBB Framework - 完全TBB原生的工业控制框架
 *
 * 这是IndustrialTBB框架的主入口文件，提供了所有核心功能的统一访问接口。
 *
 * 核心特性：
 * - 完全TBB化：所有组件都基于TBB的哲学设计
 * - 零传统锁：全部使用TBB的无锁数据结构
 * - 智能负载均衡：充分利用TBB的工作窃取
 * - 配置驱动：运行时可调节所有参数
 * - 深度可观测：与TBB的监控系统完全集成
 *
 * @version 1.0.0
 * @author IndustrialTBB Team
 */

// 版本信息
#define ITBB_VERSION_MAJOR 1
#define ITBB_VERSION_MINOR 0
#define ITBB_VERSION_PATCH 0
#define ITBB_VERSION_STRING "1.0.0"

// 核心框架
#include "itbb/core/tbb_concurrent_containers.h"
#include "itbb/core/tbb_flow_pipeline.h"
#include "itbb/core/tbb_framework.h"
#include "itbb/core/tbb_observer.h"
#include "itbb/core/tbb_task_scheduler.h"

// 设备管理
#include "itbb/devices/tbb_adwin_device.h"
#include "itbb/devices/tbb_device_factory.h"
#include "itbb/devices/tbb_device_interface.h"
#include "itbb/devices/tbb_device_pool.h"

// 配置系统
#include "itbb/config/tbb_dynamic_config.h"

// 监控系统
#include "itbb/monitoring/tbb_performance_monitor.h"

// TBB依赖
#include <oneapi/tbb.h>
#include <oneapi/tbb/info.h>

#include <iostream>

namespace itbb {
/**
 * @brief 框架版本信息结构
 */
struct FrameworkVersion {
  int major = ITBB_VERSION_MAJOR;
  int minor = ITBB_VERSION_MINOR;
  int patch = ITBB_VERSION_PATCH;
  std::string string = ITBB_VERSION_STRING;

  std::string ToString() const {
    return std::to_string(major) + "." + std::to_string(minor) + "." +
           std::to_string(patch);
  }
};

/**
 * @brief 框架初始化配置
 */
struct FrameworkInitConfig {
  // TBB配置
  size_t max_threads = tbb::info::default_concurrency();
  bool enable_numa_topology = true;

  // 调度器配置
  std::chrono::milliseconds scheduler_precision = std::chrono::milliseconds(10);
  bool enable_task_priority = true;

  // 监控配置
  bool enable_performance_monitoring = true;
  std::chrono::milliseconds monitoring_interval = std::chrono::seconds(1);

  // 配置系统
  bool enable_dynamic_config = true;
  std::string config_persistence_file = "itbb_config.json";

  // 设备池配置
  size_t max_devices = 1000;
  bool enable_device_auto_recovery = true;
  std::chrono::milliseconds device_health_check_interval =
      std::chrono::seconds(30);

  // 日志配置
  bool enable_logging = true;
  std::string log_level = "INFO";
  std::string log_file = "itbb.log";
};

/**
 * @brief IndustrialTBB框架的统一入口类
 *
 * 这个类提供了框架所有功能的统一访问接口，简化了框架的使用。
 * 它集成了所有核心组件，并提供了便捷的API。
 */
class IndustrialTBBFramework {
 public:
  /**
   * @brief 构造函数
   * @param config 框架初始化配置
   */
  explicit IndustrialTBBFramework(
      const FrameworkInitConfig& config = FrameworkInitConfig{})
      : config_(config),
        core_framework_(),
        task_scheduler_(config.max_threads),
        device_pool_(config.max_devices),
        device_factory_(),
        config_manager_(),
        performance_monitor_(),
        pipeline_manager_(),
        initialized_(false) {
    // 应用初始配置
    ApplyInitialConfiguration();
  }

  /**
   * @brief 析构函数
   */
  ~IndustrialTBBFramework() {
    if (initialized_) {
      Shutdown();
    }
  }

  // 禁用拷贝和移动
  IndustrialTBBFramework(const IndustrialTBBFramework&) = delete;
  IndustrialTBBFramework& operator=(const IndustrialTBBFramework&) = delete;
  IndustrialTBBFramework(IndustrialTBBFramework&&) = delete;
  IndustrialTBBFramework& operator=(IndustrialTBBFramework&&) = delete;

  /**
   * @brief 初始化框架
   * @return 初始化是否成功
   */
  bool Initialize() {
    if (initialized_) {
      return true;
    }

    try {
      // 初始化核心框架
      core_framework_.Initialize();

      // 设置配置持久化
      if (config_.enable_dynamic_config &&
          !config_.config_persistence_file.empty()) {
        auto persistence = std::make_unique<FileConfigPersistence>(
            config_.config_persistence_file);
        config_manager_.SetPersistenceProvider(std::move(persistence));
      }

      // 启动性能监控
      if (config_.enable_performance_monitoring) {
        performance_monitor_.SetMonitoringInterval(config_.monitoring_interval);
        performance_monitor_.EnableMonitoring(true);
      }

      // 配置设备池
      device_pool_.EnableAutoRecovery(config_.enable_device_auto_recovery);
      device_pool_.SetHealthCheckInterval(config_.device_health_check_interval);

      // 注册内置指标
      RegisterBuiltinMetrics();

      // 设置配置变化监听器
      SetupConfigurationListeners();

      initialized_ = true;

      // 记录初始化成功
      LogInfo("IndustrialTBB Framework initialized successfully");

      return true;
    } catch (const std::exception& e) {
      LogError("Failed to initialize framework: " + std::string(e.what()));
      return false;
    }
  }

  /**
   * @brief 关闭框架
   */
  void Shutdown() {
    if (!initialized_) {
      return;
    }

    LogInfo("Shutting down IndustrialTBB Framework...");

    // 按顺序关闭各个组件
    performance_monitor_.Shutdown();
    device_pool_.Shutdown();
    task_scheduler_.Shutdown();
    config_manager_.Shutdown();
    core_framework_.Shutdown();

    initialized_ = false;

    LogInfo("IndustrialTBB Framework shutdown completed");
  }

  /**
   * @brief 获取框架版本信息
   */
  static FrameworkVersion GetVersion() { return FrameworkVersion{}; }

  /**
   * @brief 检查框架是否已初始化
   */
  bool IsInitialized() const { return initialized_; }

  // ==================== 任务调度接口 ====================

  /**
   * @brief 提交任务
   * @param task 要执行的任务
   * @param priority 任务优先级
   */
  template <typename Task>
  void SubmitTask(Task&& task, TaskPriority priority = TaskPriority::kNormal) {
    task_scheduler_.SubmitTask(std::forward<Task>(task), priority);
  }

  /**
   * @brief 提交带返回值的任务
   * @param task 要执行的任务
   * @param priority 任务优先级
   * @return 任务结果的future
   */
  template <typename Task>
  auto SubmitTaskWithResult(Task&& task,
                            TaskPriority priority = TaskPriority::kNormal)
      -> std::future<decltype(task())> {
    return task_scheduler_.SubmitTaskWithResult(std::forward<Task>(task),
                                                priority);
  }

  /**
   * @brief 添加周期性任务
   * @param name 任务名称
   * @param period 执行周期
   * @param task 要执行的任务
   */
  void AddPeriodicTask(const std::string& name,
                       std::chrono::milliseconds period,
                       std::function<void()> task) {
    core_framework_.AddPeriodicTask(name, period, std::move(task));
  }

  /**
   * @brief 等待所有任务完成
   */
  void WaitForAllTasks() { task_scheduler_.WaitForAll(); }

  // ==================== 设备管理接口 ====================

  /**
   * @brief 创建设备
   * @param device_type 设备类型
   * @param device_id 设备ID
   * @param config 设备配置
   * @return 创建的设备指针
   */
  std::unique_ptr<ITbbIndustrialDevice> CreateDevice(
      TbbDeviceType device_type, const std::string& device_id,
      const TbbDeviceConfig& config) {
    return device_factory_.CreateDevice(device_type, device_id, config);
  }

  /**
   * @brief 注册设备到设备池
   * @param device_id 设备ID
   * @param device 设备实例
   * @return 注册是否成功
   */
  bool RegisterDevice(const std::string& device_id,
                      std::unique_ptr<ITbbIndustrialDevice> device) {
    return device_pool_.RegisterDevice(device_id, std::move(device));
  }

  /**
   * @brief 获取设备
   * @param device_id 设备ID
   * @return 设备指针，如果不存在返回nullptr
   */
  ITbbIndustrialDevice* GetDevice(const std::string& device_id) {
    return device_pool_.GetDevice(device_id);
  }

  /**
   * @brief 执行设备操作
   * @param device_id 设备ID
   * @param operation 要执行的操作
   * @return 操作结果
   */
  template <typename Operation>
  auto ExecuteDeviceOperation(const std::string& device_id,
                              Operation&& operation)
      -> decltype(operation(std::declval<ITbbIndustrialDevice*>())) {
    return device_pool_.ExecuteDeviceOperation(
        device_id, std::forward<Operation>(operation));
  }

  /**
   * @brief 获取所有设备ID
   */
  std::vector<std::string> GetAllDeviceIds() const {
    return device_pool_.GetAllDeviceIds();
  }

  /**
   * @brief 获取健康设备列表
   */
  std::vector<std::string> GetHealthyDevices() const {
    return device_pool_.GetHealthyDevices();
  }

  // ==================== 配置管理接口 ====================

  /**
   * @brief 设置配置值
   * @param key 配置键
   * @param value 配置值
   * @return 设置是否成功
   */
  template <typename T>
  bool SetConfig(const std::string& key, const T& value) {
    return config_manager_.SetConfig(key, value);
  }

  /**
   * @brief 获取配置值
   * @param key 配置键
   * @param default_value 默认值
   * @return 配置值
   */
  template <typename T>
  T GetConfig(const std::string& key, const T& default_value = T{}) const {
    return config_manager_.GetConfig(key, default_value);
  }

  /**
   * @brief 检查配置是否存在
   * @param key 配置键
   * @return 配置是否存在
   */
  bool HasConfig(const std::string& key) const {
    return config_manager_.HasConfig(key);
  }

  /**
   * @brief 注册配置变化监听器
   * @param key_pattern 键模式
   * @param listener 监听器函数
   * @return 监听器ID
   */
  size_t RegisterConfigChangeListener(const std::string& key_pattern,
                                      ConfigChangeListener listener) {
    return config_manager_.RegisterChangeListener(key_pattern,
                                                  std::move(listener));
  }

  // ==================== 性能监控接口 ====================

  /**
   * @brief 创建计数器指标
   * @param name 指标名称
   * @return 计数器指标
   */
  std::shared_ptr<TbbCounterMetric> CreateCounter(const std::string& name) {
    return performance_monitor_.CreateCounter(name);
  }

  /**
   * @brief 创建仪表指标
   * @param name 指标名称
   * @return 仪表指标
   */
  std::shared_ptr<TbbGaugeMetric> CreateGauge(const std::string& name) {
    return performance_monitor_.CreateGauge(name);
  }

  /**
   * @brief 创建计时器指标
   * @param name 指标名称
   * @return 计时器指标
   */
  std::shared_ptr<TbbTimerMetric> CreateTimer(const std::string& name) {
    return performance_monitor_.CreateTimer(name);
  }

  /**
   * @brief 获取性能快照
   * @return 系统性能快照
   */
  TbbPerformanceMonitor::SystemPerformanceSnapshot GetPerformanceSnapshot()
      const {
    return performance_monitor_.GetPerformanceSnapshot();
  }

  /**
   * @brief 导出指标数据
   * @param format 导出格式（json/prometheus）
   * @return 导出的数据字符串
   */
  std::string ExportMetrics(const std::string& format = "json") const {
    return performance_monitor_.ExportMetrics(format);
  }

  // ==================== 数据流水线接口 ====================

  /**
   * @brief 创建数据流水线
   * @param name 流水线名称
   * @return 流水线管理器
   */
  std::shared_ptr<TbbAdvancedPipeline> CreatePipeline(const std::string& name) {
    auto pipeline = std::make_shared<TbbAdvancedPipeline>();

    PipelineMap::accessor accessor;
    pipelines_.insert(accessor, name);
    accessor->second = pipeline;

    return pipeline;
  }

  /**
   * @brief 获取数据流水线
   * @param name 流水线名称
   * @return 流水线管理器
   */
  std::shared_ptr<TbbAdvancedPipeline> GetPipeline(const std::string& name) {
    PipelineMap::const_accessor accessor;
    if (pipelines_.find(accessor, name)) {
      return accessor->second;
    }
    return nullptr;
  }

  // ==================== 系统信息接口 ====================

  /**
   * @brief 获取系统信息
   */
  struct SystemInfo {
    FrameworkVersion framework_version;
    size_t hardware_concurrency;
    size_t numa_nodes;
    bool tbb_version_info;

    // 运行时统计
    std::chrono::steady_clock::time_point startup_time;
    std::chrono::nanoseconds uptime;

    // 组件状态
    bool core_framework_initialized;
    bool task_scheduler_running;
    bool device_pool_active;
    bool performance_monitoring_enabled;

    // 资源使用情况
    size_t total_devices;
    size_t healthy_devices;
    size_t active_tasks;
    size_t total_metrics;
  };

  SystemInfo GetSystemInfo() const {
    SystemInfo info;

    info.framework_version = GetVersion();
    info.hardware_concurrency = tbb::info::default_concurrency();
    info.numa_nodes = 1;  // 简化实现
    info.tbb_version_info = true;

    info.startup_time = startup_time_;
    info.uptime = std::chrono::steady_clock::now() - startup_time_;

    info.core_framework_initialized = initialized_;
    info.task_scheduler_running = initialized_;
    info.device_pool_active = initialized_;
    info.performance_monitoring_enabled = config_.enable_performance_monitoring;

    auto pool_stats = device_pool_.GetPoolStats();
    info.total_devices = pool_stats.total_devices;
    info.healthy_devices = pool_stats.healthy_devices;

    auto task_stats = task_scheduler_.GetTaskStats();
    info.active_tasks = 0;  // 需要从task_stats获取

    auto monitoring_stats = performance_monitor_.GetMonitoringStats();
    info.total_metrics = monitoring_stats.total_metrics;

    return info;
  }

  /**
   * @brief 获取框架健康状态
   */
  struct HealthStatus {
    bool overall_healthy;
    std::vector<std::string> issues;
    double health_score;  // 0.0 - 1.0

    struct ComponentHealth {
      std::string component_name;
      bool healthy;
      std::string status_message;
    };

    std::vector<ComponentHealth> component_health;
  };

  HealthStatus GetHealthStatus() const {
    HealthStatus status;
    status.overall_healthy = true;
    status.health_score = 1.0;

    // 检查各个组件的健康状态
    if (!initialized_) {
      status.overall_healthy = false;
      status.issues.push_back("Framework not initialized");
      status.health_score -= 0.5;
    }

    // 检查设备池健康状态
    auto pool_stats = device_pool_.GetPoolStats();
    if (pool_stats.total_devices > 0) {
      double device_health_ratio =
          static_cast<double>(pool_stats.healthy_devices) /
          pool_stats.total_devices;
      if (device_health_ratio < 0.8) {
        status.issues.push_back("Low device health ratio: " +
                                std::to_string(device_health_ratio));
        status.health_score -= (1.0 - device_health_ratio) * 0.3;
      }

      status.component_health.push_back(
          {"DevicePool", device_health_ratio >= 0.8,
           std::to_string(pool_stats.healthy_devices) + "/" +
               std::to_string(pool_stats.total_devices) + " devices healthy"});
    }

    // 检查任务调度器健康状态
    status.component_health.push_back(
        {"TaskScheduler", initialized_,
         initialized_ ? "Running" : "Not initialized"});

    // 检查性能监控健康状态
    status.component_health.push_back(
        {"PerformanceMonitor", config_.enable_performance_monitoring,
         config_.enable_performance_monitoring ? "Active" : "Disabled"});

    status.overall_healthy = status.health_score >= 0.7;

    return status;
  }

  // ==================== 便捷方法 ====================

  /**
   * @brief 快速创建ADwin设备
   * @param device_id 设备ID
   * @param ip_address IP地址
   * @param port 端口号
   * @return 创建并注册是否成功
   */
  bool CreateAndRegisterAdwinDevice(const std::string& device_id,
                                    const std::string& ip_address,
                                    uint16_t port = 6543) {
    try {
      TbbAdwinConfig config;
      config.ip_address = ip_address;
      config.port.store(port);

      auto device = CreateDevice(TbbDeviceType::kAdwin, device_id, config);
      return RegisterDevice(device_id, std::move(device));
    } catch (const std::exception& e) {
      LogError("Failed to create ADwin device: " + std::string(e.what()));
      return false;
    }
  }

  /**
   * @brief 批量连接所有设备
   * @return 连接是否成功
   */
  bool ConnectAllDevices() {
    try {
      return device_pool_.ConnectAllDevicesAsync().get();
    } catch (const std::exception& e) {
      LogError("Failed to connect all devices: " + std::string(e.what()));
      return false;
    }
  }

  /**
   * @brief 运行框架（阻塞直到收到停止信号）
   */
  void Run() {
    if (!initialized_) {
      throw std::runtime_error("Framework not initialized");
    }

    LogInfo("IndustrialTBB Framework is running...");

    // 这里可以添加信号处理，等待停止信号
    // 简化实现：等待用户输入
    std::cout << "Press Enter to stop the framework..." << std::endl;
    std::cin.get();

    LogInfo("Shutdown signal received");
  }

 private:
  FrameworkInitConfig config_;

  // 核心组件
  IndustrialFramework core_framework_;
  TbbAdvancedTaskScheduler task_scheduler_;
  TbbDevicePool device_pool_;
  TbbDeviceFactory device_factory_;
  TbbDynamicConfigManager config_manager_;
  TbbPerformanceMonitor performance_monitor_;

  // 流水线管理
  using PipelineMap =
      tbb::concurrent_hash_map<std::string,
                               std::shared_ptr<TbbAdvancedPipeline>>;
  PipelineMap pipelines_;

  // 状态变量
  std::atomic<bool> initialized_;
  std::chrono::steady_clock::time_point startup_time_{
      std::chrono::steady_clock::now()};

  // 应用初始配置
  void ApplyInitialConfiguration() {
    // 设置TBB线程数
    if (config_.max_threads > 0) {
      core_framework_.SetMaxThreads(config_.max_threads);
    }

    // 设置调度器精度
    core_framework_.SetSchedulerPrecision(config_.scheduler_precision);
  }

  // 注册内置指标
  void RegisterBuiltinMetrics() {
    // 创建系统级指标
    performance_monitor_.CreateGauge("system.cpu.utilization");
    performance_monitor_.CreateGauge("system.memory.usage");
    performance_monitor_.CreateGauge("system.threads.active");
    performance_monitor_.CreateCounter("system.tasks.total");
    performance_monitor_.CreateTimer("system.task.duration");

    // 创建设备相关指标
    performance_monitor_.CreateGauge("devices.total");
    performance_monitor_.CreateGauge("devices.healthy");
    performance_monitor_.CreateCounter("devices.operations.total");
    performance_monitor_.CreateCounter("devices.operations.failed");
    performance_monitor_.CreateTimer("devices.operation.duration");
  }

  // 设置配置监听器
  void SetupConfigurationListeners() {
    // 监听线程数配置变化
    config_manager_.RegisterChangeListener(
        "framework.max_threads", [this](const ConfigChangeEvent& event) {
          if (auto new_threads = std::get_if<double>(&event.new_value)) {
            core_framework_.SetMaxThreads(static_cast<size_t>(*new_threads));
            task_scheduler_.SetMaxThreads(static_cast<size_t>(*new_threads));
          }
        });

    // 监听调度精度配置变化
    config_manager_.RegisterChangeListener(
        "framework.scheduler_precision",
        [this](const ConfigChangeEvent& event) {
          if (auto new_precision = std::get_if<double>(&event.new_value)) {
            auto precision =
                std::chrono::milliseconds(static_cast<int64_t>(*new_precision));
            core_framework_.SetSchedulerPrecision(precision);
          }
        });

    // 监听监控配置变化
    config_manager_.RegisterChangeListener(
        "monitoring.*", [this](const ConfigChangeEvent& event) {
          if (event.key == "monitoring.enabled") {
            if (auto enabled = std::get_if<bool>(&event.new_value)) {
              performance_monitor_.EnableMonitoring(*enabled);
            }
          } else if (event.key == "monitoring.interval") {
            if (auto interval = std::get_if<double>(&event.new_value)) {
              auto ms =
                  std::chrono::milliseconds(static_cast<int64_t>(*interval));
              performance_monitor_.SetMonitoringInterval(ms);
            }
          }
        });
  }

  // 日志方法
  void LogInfo(const std::string& message) {
    if (config_.enable_logging) {
      std::cout << "[INFO] " << message << std::endl;
    }
  }

  void LogError(const std::string& message) {
    if (config_.enable_logging) {
      std::cerr << "[ERROR] " << message << std::endl;
    }
  }
};

// ==================== 全局便捷函数 ====================

/**
 * @brief 获取全局框架实例
 */
IndustrialTBBFramework& GetGlobalFramework() {
  static IndustrialTBBFramework instance;
  return instance;
}

/**
 * @brief 初始化全局框架
 * @param config 初始化配置
 * @return 初始化是否成功
 */
bool InitializeFramework(
    const FrameworkInitConfig& config = FrameworkInitConfig{}) {
  return GetGlobalFramework().Initialize();
}

/**
 * @brief 关闭全局框架
 */
void ShutdownFramework() { GetGlobalFramework().Shutdown(); }

/**
 * @brief 便捷的任务提交函数
 */
template <typename Task>
void SubmitTask(Task&& task, TaskPriority priority = TaskPriority::kNormal) {
  GetGlobalFramework().SubmitTask(std::forward<Task>(task), priority);
}

/**
 * @brief 便捷的配置设置函数
 */
template <typename T>
bool SetConfig(const std::string& key, const T& value) {
  return GetGlobalFramework().SetConfig(key, value);
}

/**
 * @brief 便捷的配置获取函数
 */
template <typename T>
T GetConfig(const std::string& key, const T& default_value = T{}) {
  return GetGlobalFramework().GetConfig(key, default_value);
}
}  // namespace itbb

#endif  // ITBB_H_
